/*
 * The MIT License
 * Copyright (c) 2009 Thinkpot.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package thinkpot.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.rmi.server.UID;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * @author S.Ito
 */
public class FileUploadServlet extends HttpServlet {

	/** シリアル・バージョンUID */
	private static final long serialVersionUID = -566735040446249028L;

	/**
	 * @see javax.servlet.http.HttpServlet#doPut(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
		throws ServletException, IOException {

		final FileItemFactory factory = new PersistentDiskFileItemFactory();
		final ServletFileUpload sfu = new ServletFileUpload(factory);
		sfu.setSizeMax(-1);

		final List fileItems;

		try {
			fileItems = sfu.parseRequest(req);
		} catch (FileUploadException e) {
			throw new ServletException(e);
		}

		final HttpSession session = req.getSession();
		SessionManagedFileContainer fc = (SessionManagedFileContainer) session.getAttribute(getClass().getName());

		if (null == fc) {
			fc = new SessionManagedFileContainer();
			session.setAttribute(getClass().getName(), fc);
		}

		final List fileIDs = new ArrayList();
		final List fileNames = new ArrayList();

		for (Iterator i = fileItems.iterator(); i.hasNext();) {
			final FileItem item = (FileItem) i.next();

			if ((null == item.getName()) || (0 == item.getName().trim().length())) {
				continue;
			}

			if ((!item.isFormField()) && (item instanceof PersistentDiskFileItem)) {
				final PersistentDiskFileItem pdfi = (PersistentDiskFileItem) item;
				final UID uid = new UID();

				fc.putFile(uid.toString(), pdfi.toFile());

				fileIDs.add(uid.toString());
				fileNames.add(item.getName());
			}
		}

		resp.setContentType("text/html; charset=UTF-8");
		final PrintWriter w = resp.getWriter();
		w.print("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Strict//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">");
		w.print("<html>");
		w.print("<head>");
		w.print("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">");
		w.print("<meta http-equiv=\"Content-Script-Type\" content=\"text/javascript\">");
		w.println("<script type=\"text/javascript\">");
		w.println("<!--");
		w.println("window.onload = function() {");
		w.println("	if (window.parent) {");
		w.print("		window.parent.onUploaded(eval(\"([");

		for (int i = 0; i < fileIDs.size(); i++) {
			final String fileID = (String) fileIDs.get(i);
			final String fileName = (String) fileNames.get(i);

			if (0 != i) {
				w.print(",");
			}

			w.print("{'id':'");
			w.print(fileID);
			w.print("','name':'");
			w.print(fileName);
			w.print("'}");
		}

		w.println("])\"));");
		w.println("	}");
		w.println("}");
		w.println("//-->");
		w.print("</script>");
		w.print("</head>");
		w.print("<body></body>");
		w.print("</html>");
	}
}
